<?php
declare (strict_types=1);

namespace app\admin\middleware;

use app\api\exception\HttpExceptionHandle;
use app\common\auth\JwtAuth;
use app\common\lib\HttpError;
use app\common\lib\ResponseJson;
use Closure;
use think\facade\Cache;

/**
 * | Notes：Jwt中间件
 * +----------------------------------------------------------------------
 * | PHP Version 7.2+
 * +----------------------------------------------------------------------
 * | Copyright (c) 2011-2020 https://www.xxq.com.cn, All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 和好 <389123492@qq.com>
 * +----------------------------------------------------------------------
 * | Date: 2020/4/19 14:53
 * +----------------------------------------------------------------------
 */
class Jwt
{
    use ResponseJson;

    public function handle($request, Closure $next)
    {

        $token = trim($request->header('token'));

        if (empty($token)) throw new HttpExceptionHandle(HttpError::NO_TOKEN_ERR);

        //实例化
        $jwtauth = JwtAuth::getInstance();
        // 放入token
        $jwtauth->setToken($token);
        // 实例化值
        try {
            $jwtauth->parserToken();
        } catch (\Exception $e) {
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR);
        }
        // 获得userid
        $uuid = $jwtauth->getUuid();
        if(empty($uuid)){
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR);
        }

        // 使用Redis缓存
        if( empty(Cache::store('redis')->get('admin_'.$token)) ){
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR);
        }

        return $next($request);

        //if ($expire_time <= 0) throw new HttpExceptionHandle(HttpError::INVALID_TOKEN_ERR);

        /*if ($jwtauth->setToken($token)->parserToken()->verify() !== true || $jwtauth->setToken($token)->parserToken()->validate() !== true) {
            throw new HttpExceptionHandle(HttpError::TOKEN_ERR);
        }

        return $next($request);*/
    }
}